<template>
  <div class="alloc-menu">
    <el-card>
      <el-tree
        :data="menus"
        :props="defaultProps"
        show-checkbox
        default-expand-all
        :default-checked-keys="checkedKeys"
      ></el-tree>
      <div style="margin: 20px;">
        <el-button @click="resetChecked">清空</el-button>
        <el-button type="primary"
        @click="onSave">保存</el-button>
      </div>
    </el-card>
  </div>
</template>

<script>
import { getMenuNodeList, allocateRoleMenus, getRoleMenus } from '@/services/menu'
export default {
  name: 'AllocMenu',
  props: {
    roleId: {
      type: [String, Number],
      required: true
    }
  },
  data () {
    return {
      nemus: [],
      defaultProps: {
        children: 'subMenuList',
        label: 'name'
      },
      checkedKeys: []
    }
  },
  created () {
    this.loadMenus()
    this.loadRoleMenus()
  },
  methods: {
    async loadMenus () {
      const { data } = await getMenuNodeList()
      if (data.code === '000000') {
        this.menus = data.dataa
      }
    },
    async loadRoleMenus () {
      // 请求角色拥有的菜单列表
      const { data } = await getRoleMenus(this.roleId)
      if (data.code === '000000') {
        // 获取选中的数据
        this.getCheckedKeys()
      }
    },
    // 数据筛选功能
    getCheckedKeys (menus) {
      menus.forEach(menu => {
        // 检测是否存在子数据，如果有，递归查找
        //   - 同时说明当前节点为‘父节点’，不能存入，否则勾选会导致子选项全选，设置 return
        if (menu.subMenuList) {
          return this.getCheckedKeys(menu.subMenuList)
        }
        // 存储选中数据的 id
        if (menu.selected) {
          // this.checkedKeys.push(menu.id)
          this.checkedKeys = [...this.checkedKeys, menu.id]
        }
      })
    },
    async onSave () {
      const { data } = await allocateRoleMenus({
        roleId: this.roleId,
        menuIdList: this.$refs['menu-tree'].getCheckedKeys()
      })
      if (data.code === '000000') {
        this.$message.success('分配菜单成功')
        this.router.push('/role')
      }
    },
    resetChecked () {
      this.$refs['menu-tree'].setCheckedKeys([])
    }
  }
}
</script>

<style lang="scss" scoped></style>
